package com.boesch.electroOffice.utils;

import java.util.ArrayList;
import java.util.List;

import com.liferay.portal.NoSuchRoleException;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.model.Role;
import com.liferay.portal.model.User;
import com.liferay.portal.service.ClassNameLocalServiceUtil;
import com.liferay.portal.service.RoleLocalServiceUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portlet.expando.model.ExpandoTableConstants;
import com.liferay.portlet.expando.model.ExpandoValue;
import com.liferay.portlet.expando.service.ExpandoValueLocalServiceUtil;

public class RoleUtils {
	
	private static final Log log = LogFactoryUtil.getLog(RoleUtils.class);

	/**
	 * Returns all roles(regular, site and organization roles) from Liferay DB
	 * 
	 * @return List<Role> roles
	 */
	public static List<Role> getAllRoles() {
		List<Role> roles = new ArrayList<Role>();
		try {
			roles = RoleLocalServiceUtil.getRoles(0, RoleLocalServiceUtil.getRolesCount());
		} catch (SystemException e) {
			log.error("Failed to read roles from liferay database!", e);
		}
		return roles;
	}

	/**
	 * Returns a list of liferay roles which has the expando value
	 * Boeschrolle set to true
	 * 
	 * @return List<Role> boeschRoles
	 */
	public static List<Role> getAllBoeschRoles() {
		String customAttributeName = "Boeschrolle";
		String customAttributeValue = "true";
		
		long classNameId = ClassNameLocalServiceUtil.getClassNameId(Role.class);
		long companyId = PortalUtil.getDefaultCompanyId();
		
		List<Role> roles = new ArrayList<Role>();
		List<ExpandoValue> values = new ArrayList<ExpandoValue>();
		try {
			values = ExpandoValueLocalServiceUtil.getColumnValues(companyId, classNameId, 
												ExpandoTableConstants.DEFAULT_TABLE_NAME, customAttributeName, customAttributeValue, -1, -1);
		
			Role role = null;       
			for (int i = 0; i < values.size(); i++) {
				long roleId = values.get(i).getClassPK();
				try {
					role =  RoleLocalServiceUtil.getRole(roleId);
					roles.add(role);
				} catch(NoSuchRoleException e) {
					log.error("No role found with id: " + roleId);
				}
			}
		} catch (SystemException e) {
			log.error("Failed to load boesch roles from dataaccess.", e);
		} catch (PortalException e) {
			log.error("Failed to load boesch roles from dataaccess.", e);
		}
		return roles;
	}

	public static List<Role> getCurrentUsersRoles() {
		List<Role> roles = new ArrayList<Role>();
		User user = UserUtils.getCurrentUser();
		try {
			roles = user.getRoles();
		} catch (SystemException e) {
			log.error("Failed to load roles from user: " + user.getUserId());
		}
		return roles;
	}
}
